package com.yunma.dialog;

import com.common.dict.Constant2;
import com.common.util.SystemHWUtil;
import com.http.util.HttpSocketUtil;
import com.io.hw.file.util.FileUtils;
import com.io.hw.json.HWJacksonUtils;
import com.string.widget.util.ValueWidget;
import com.swing.component.AssistPopupTextArea;
import com.swing.component.AssistPopupTextField;
import com.swing.component.ComponentUtil;
import com.swing.dialog.DialogUtil;
import com.swing.dialog.GenericDialog;
import com.swing.dialog.toast.ToastMessage;
import com.swing.messagebox.GUIUtil23;
import com.yunma.autotest.AutoTestPanel;
import org.codehaus.jackson.JsonParseException;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.List;

public class UploadPicDialog extends GenericDialog {

    private JPanel contentPane;
    private AssistPopupTextField pathTextField;
    /***
     * 文件后缀名<br />
     * 支持多后缀名:以空格,逗号,分号或冒号分隔
     */
    private AssistPopupTextField suffixTextField;
    private AssistPopupTextArea resultTextArea;
    private JButton btnUpload;
    /***
     * 拖拽的文件(可能有多个)
     */
    private List<File> dragedFiles;
    private AutoTestPanel autoTestPanel;
    private JPanel panel_1;
    private JCheckBox chckbxSamefilename;
    /***
     * 上传图片时,指定文件名称
     */
    private AssistPopupTextField specifiedfilenameTF;
    private JSeparator separator;

    /**
     * Launch the application.
     */
    /*public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UploadPicDialog frame = new UploadPicDialog();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
*/

    /**
     * Create the frame.
     */
    public UploadPicDialog(AutoTestPanel autoTestPanel) {
        this.autoTestPanel = autoTestPanel;
//		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setModal(true);
//		setBounds(100, 100, 450, 300);
        setLoc(850, 500);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        GridBagLayout gbl_contentPane = new GridBagLayout();
        gbl_contentPane.columnWidths = new int[]{0, 0, 0};
        gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0};
        gbl_contentPane.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
        gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
        contentPane.setLayout(gbl_contentPane);

        JLabel label = new JLabel("图片路径");
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.insets = new Insets(0, 0, 5, 5);
        gbc_label.anchor = GridBagConstraints.EAST;
        gbc_label.gridx = 0;
        gbc_label.gridy = 0;
        contentPane.add(label, gbc_label);

        pathTextField = new AssistPopupTextField();
        pathTextField.placeHolder("可以是目录");
        drag(pathTextField);
        GridBagConstraints gbc_pathTextField = new GridBagConstraints();
        gbc_pathTextField.insets = new Insets(0, 0, 5, 0);
        gbc_pathTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_pathTextField.gridx = 1;
        gbc_pathTextField.gridy = 0;
        contentPane.add(pathTextField, gbc_pathTextField);
        pathTextField.setColumns(10);

        JLabel label_1 = new JLabel("后缀名(不区分大小写)");
        GridBagConstraints gbc_label_1 = new GridBagConstraints();
        gbc_label_1.anchor = GridBagConstraints.EAST;
        gbc_label_1.insets = new Insets(0, 0, 5, 5);
        gbc_label_1.gridx = 0;
        gbc_label_1.gridy = 1;
        contentPane.add(label_1, gbc_label_1);

        panel_1 = new JPanel();
        GridBagConstraints gbc_panel_1 = new GridBagConstraints();
        gbc_panel_1.anchor = GridBagConstraints.WEST;
        gbc_panel_1.insets = new Insets(0, 0, 5, 0);
        gbc_panel_1.fill = GridBagConstraints.VERTICAL;
        gbc_panel_1.gridx = 1;
        gbc_panel_1.gridy = 1;
        contentPane.add(panel_1, gbc_panel_1);

        //文件后缀名
        suffixTextField = new AssistPopupTextField();
        panel_1.add(suffixTextField);
        suffixTextField.setColumns(10);

        separator = new JSeparator();
        panel_1.add(separator);

        chckbxSamefilename = new JCheckBox("sameFileName");
        panel_1.add(chckbxSamefilename);
        suffixTextField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                btnUpload.doClick();
            }
        });

        specifiedfilenameTF = new AssistPopupTextField();
        specifiedfilenameTF.setColumns(20);
        specifiedfilenameTF.placeHolder("指定文件名");
        panel_1.add(specifiedfilenameTF);

        JPanel panel = new JPanel();
        GridBagConstraints gbc_panel = new GridBagConstraints();
        gbc_panel.insets = new Insets(0, 0, 5, 0);
        gbc_panel.gridwidth = 2;
        gbc_panel.fill = GridBagConstraints.BOTH;
        gbc_panel.gridx = 0;
        gbc_panel.gridy = 2;
        contentPane.add(panel, gbc_panel);

        btnUpload = new JButton("upload");
        btnUpload.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String filePath = pathTextField.getText2();
                final File file = new File(filePath);
                if (ValueWidget.isNullOrEmpty(dragedFiles)) {
                    if (!file.exists()) {
                        ToastMessage.toast("文件路径不正确", 2000, Color.red);
                        return;
                    }
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        uploadAction(file);
                    }
                }).start();
            }
        });
        panel.add(btnUpload);

        JScrollPane scrollPane = new JScrollPane();
        GridBagConstraints gbc_scrollPane = new GridBagConstraints();
        gbc_scrollPane.gridwidth = 2;
        gbc_scrollPane.fill = GridBagConstraints.BOTH;
        gbc_scrollPane.gridx = 0;
        gbc_scrollPane.gridy = 3;
        contentPane.add(scrollPane, gbc_scrollPane);

        resultTextArea = new AssistPopupTextArea();
        drag(resultTextArea);
        resultTextArea.setLineWrap(true);
        resultTextArea.setWrapStyleWord(true);
        resultTextArea.setEditable(false);
        scrollPane.setViewportView(resultTextArea);
        DialogUtil.escape2CloseDialog(this);
    }

    public void uploadAction(File file) {
        btnUpload.setEnabled(false);
        List<String> imgTagList = new ArrayList<String>();
        boolean sameFileName = chckbxSamefilename.isSelected();
        String specifiedfilename = specifiedfilenameTF.getText2();
        Map<String, String> parameters = null;
        parameters = new HashMap<>();
        parameters.put(Constant2.PARAMETER_SAME_FILE_NAME, sameFileName ? Constant2.PARAMETER_VALUE_ON : SystemHWUtil.EMPTY);
        parameters.put("fileName", specifiedfilename);
        ComponentUtil.appendResult(resultTextArea, (parameters == null ? null : (SystemHWUtil.CRLF + parameters.toString())), true, false);
        if (ValueWidget.isNullOrEmpty(dragedFiles)) {
            String suffixStr = suffixTextField.getText2();
            String[] suffixArr = suffixStr.split("[\\s,;:]");//以空格,逗号,分号或冒号分隔
//                        System.out.println(SystemHWUtil.formatArr(suffixArr,","));

            Set<String> suffixSet = new HashSet<String>(Arrays.asList(suffixArr));//过滤掉相同的


            updateAction(imgTagList, parameters, suffixSet, file);
        } else {//有拖拽的文件
            ComponentUtil.appendResult(resultTextArea, SystemHWUtil.EMPTY, true, false);
            uploadMutipFiles(imgTagList, dragedFiles, parameters);
            dragedFiles = null;
        }
        uploadedSuccess(imgTagList);
    }

    public void updateAction(List<String> imgTagList, Map<String, String> parameters, Set<String> suffixSet, File file) {
        if (file.isDirectory()) {
            List<File> allFile = new ArrayList<File>();
            for (String suffix : suffixSet) {
                List<File> list = FileUtils.getListFiles(file, suffix);
                allFile.addAll(list);
            }

            uploadMutipFiles(imgTagList, allFile, parameters);
        } else {
            String fileName = file.getName();
            imgTagList.add(uploadFile2(file, fileName, parameters));
        }
    }

    public void uploadMutipFiles(List<String> imgTagList, List<File> allFile, Map<String, String> parameters) {
        for (File file1 : allFile) {
            String fileName = file1.getName();
            if (file1.isDirectory()) {
                if (autoTestPanel.getGlobalConfig().isUploadSupportFolder()) {
                    File[] subFiles = file1.listFiles();
                    uploadMutipFiles(imgTagList, Arrays.asList(subFiles), parameters);
                } else {
                    GUIUtil23.errorDialog("\"" + fileName + "\" 是文件夹,暂时不支持文件夹");
                    break;
                }
            } else {
                imgTagList.add(uploadFile2(file1, fileName, parameters));
            }
        }
    }

    /***
     * 上传成功后的日志打印
     * @param imgTagList
     */
    public void uploadedSuccess(List<String> imgTagList) {
        ComponentUtil.appendResult(resultTextArea, SystemHWUtil.EMPTY, true, false);
        ComponentUtil.appendResult(resultTextArea, SystemHWUtil.formatArr(imgTagList, "<br>"), true, false);
        ComponentUtil.appendResult(resultTextArea, "共计" + imgTagList.size() + " 个", false, false);
        this.autoTestPanel.appendStr2LogFile(HWJacksonUtils.getJsonP(imgTagList), true);
        btnUpload.setEnabled(true);
    }

    private String uploadFile2(File file, String fileName, Map<String, String> parameters) {
        try {
            FileInputStream ins = new FileInputStream(file);
            String result = HttpSocketUtil.uploadFile("http://blog.yhskyc.com/convention2/ajax_image/upload",
                    ins, parameters, fileName);

            Map map = (Map) HWJacksonUtils.deSerialize(result, Map.class);
            String fullUrl = (String) map.get("fullUrl");
            ComponentUtil.appendResult(resultTextArea, fullUrl, false, false);
            this.autoTestPanel.appendStr2LogFile(fullUrl, false);
            return ValueWidget.unescapeHTML((String) map.get("imgTag"));
        } catch (JsonParseException e1) {
            e1.printStackTrace();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return fileName;
    }

    @Override
    public void dragResponse(List<File> list, Component component) {
        DialogUtil.dragResponseAllFiles(list, component);
        dragedFiles = list;
        if (autoTestPanel.getGlobalConfig().isAutoUploadImmediately()) {
            btnUpload.doClick();
        }
    }
}
